package net.k3rnel.abugadro.gcodes;

import net.k3rnel.abugadro.AbugadroContentProvider;
import net.k3rnel.abugadro.ProjectsDB;
import net.k3rnel.abugadro.R;
import net.k3rnel.abugadro.Project.Projects;
import net.k3rnel.abugadro.gcodes.beans.Issue.Issues;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler;
import net.k3rnel.abugadro.util.SyncService;
import net.k3rnel.abugadro.util.UIUtils;
import net.k3rnel.abugadro.util.NotifyingAsyncQueryHandler.AsyncQueryListener;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.BaseColumns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class IssuesList extends ListActivity implements AsyncQueryListener{

	private IssuesAdapter mAdapter;
	private NotifyingAsyncQueryHandler mHandler;
	private int gcodeId;
	private String projName;
	private int mState = 0;
	private final SyncService mSyncService = new SyncService();
	private SharedPreferences prefsPrivate;
	public static final  String ABUGADRO_PREFS = "abugadro.prefs";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_gcode_issues);
		final Uri issuesUri = getIntent().getData();
		gcodeId = Integer.parseInt(issuesUri.getPathSegments().get(1));
		final int projectId = ProjectsDB.getInstance().getProjectIdbyGoogleId(getContentResolver(),gcodeId);
		projName = ProjectsDB.getInstance().getProjectName(getContentResolver(), projectId);
		((TextView) findViewById(R.id.title_text)).setText(
				projName != null ? projName : getTitle());
		mAdapter = new IssuesAdapter(this);
		setListAdapter(mAdapter);

		mHandler = new NotifyingAsyncQueryHandler(getContentResolver(), this);
		final String action = getIntent().getAction();
		if ("net.k3rnel.abugadro.OPEN".equals(action) && savedInstanceState == null) {
			mState = 2; //Open
			mHandler.startQuery(issuesUri,IssuesQuery.PROJECTION,Issues.STATE+"='open' and "+Issues.GCODE_ID+" = "+gcodeId,null,Issues.DEFAULT_SORT);
		}else if ("net.k3rnel.abugadro.CLOSED".equals(action) && savedInstanceState == null) {
			mState = 1;//Closed
			mHandler.startQuery(issuesUri,IssuesQuery.PROJECTION,Issues.STATE+"='closed' and "+Issues.GCODE_ID+" = "+gcodeId,null,Issues.DEFAULT_SORT);
		}else{
			mState = 0; //All
			mHandler.startQuery(issuesUri, IssuesQuery.PROJECTION,Issues.GCODE_ID+" = "+gcodeId,null,Issues.DEFAULT_SORT);
		}
//		prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
//		if(prefsPrivate.getBoolean("IssuesList-first",true)){ //It's true for first-run
//			Toast.makeText(getApplicationContext(), "Press menu to display sorting options.", Toast.LENGTH_LONG).show();
//			prefsPrivate = getSharedPreferences(ABUGADRO_PREFS, Context.MODE_PRIVATE);
//			Editor prefsPrivateEditor = prefsPrivate.edit();
//			prefsPrivateEditor.putBoolean("IssuesList-first",false);
//			prefsPrivateEditor.commit();
//		}
	}
	@Override
	public boolean moveTaskToBack(boolean nonRoot) {
		mSyncService.stopThread();
		return super.moveTaskToBack(nonRoot);
	}
	/** {@inheritDoc} */
	public void onQueryComplete(int token, Object cookie, Cursor cursor) {
		startManagingCursor(cursor);
		mAdapter.changeCursor(cursor);
		final String action = getIntent().getAction();
		final Uri issuesUri = getIntent().getData();
		if(mSyncService.isSync())
			if ("net.k3rnel.abugadro.OPEN".equals(action)) {
				mState = 2;//Closed
				mHandler.startQuery(issuesUri,IssuesQuery.PROJECTION,Issues.STATE+"='open' and "+Issues.GCODE_ID+" = "+gcodeId,null,Issues.DEFAULT_SORT);
			}else if ("net.k3rnel.abugadro.CLOSED".equals(action)) {
				mState = 1;//Closed
				mHandler.startQuery(issuesUri,IssuesQuery.PROJECTION,Issues.STATE+"='closed' and "+Issues.GCODE_ID+" = "+gcodeId,null,Issues.DEFAULT_SORT);
			}else{
				mState = 0; //All
				mHandler.startQuery(issuesUri, IssuesQuery.PROJECTION, Issues.DEFAULT_SORT);
			}
	}


	/** Handle "search" title-bar action. */
	public void onSearchClick(View v) {
		//		UIUtils.goSearch(this);
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Okay", null)
		.setTitle("Sorry Dude!")
		.setMessage("Search function isn't ready!")
		.create();
		ad.show();
	}

	/** Handle "alert" title-bar action. */
	public void onAlertClick(View v) {
		AlertDialog ad = new AlertDialog.Builder(this)
		.setPositiveButton("Okay", null)
		.setTitle("Hold it!")
		.setMessage("No Internets. Will work with offline data")
		.create();
		ad.show();
		updateRefreshStatus();
	}
	/** Handle "home" title-bar action. */
	public void onHomeClick(View v) {
		UIUtils.goHome(this);
	}
	/** {@inheritDoc} */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		mSyncService.stopThread();
		if (id >= 0) {
			final Cursor cursor = (Cursor)mAdapter.getItem(position);
			final String issueId = cursor.getString(cursor.getColumnIndex(Issues.ISSUE_ID));
			final Uri projectURI = Uri.parse("content://"+ AbugadroContentProvider.AUTHORITY + "/gcode/"+gcodeId+"/issues/"+issueId);
			Intent i = new Intent(getApplicationContext(),BrowseIssue.class);
			i.setAction(android.content.Intent.ACTION_VIEW);
			i.putExtra(Intent.EXTRA_TITLE,projName);
			i.putExtra("projName",projName);
			i.setDataAndType(projectURI,"vnd.android.cursor.dir/*");

			startActivity(i);

		}

	}
	/** Handle "refresh" title-bar action. */
	public void onRefreshClick(View v) {
		if(!mSyncService.isSync())
			mSyncService.startThread(handler, getContentResolver(), getIntent().getData(), mState);
	}
	private void displayAlert() {
		findViewById(R.id.gcode_home_btn_refresh).setVisibility(View.GONE);
		findViewById(R.id.gcode_home_btn_refresh_progress).setVisibility(View.GONE);
		findViewById(R.id.gcode_home_btn_alert).setVisibility(View.VISIBLE);
	}
	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if(msg.getData().getInt("status")==1){
				updateRefreshStatus();
				final String action = getIntent().getAction();
				final Uri issuesUri = getIntent().getData();
				if ("net.k3rnel.abugadro.OPEN".equals(action)) {
					mHandler.startQuery(issuesUri,IssuesQuery.PROJECTION,Issues.STATE+"='open' and "+Issues.GCODE_ID+" = "+gcodeId,null,Issues.DEFAULT_SORT);
				}else if ("net.k3rnel.abugadro.CLOSED".equals(action)) {
					mState = 2;//Closed
					mHandler.startQuery(issuesUri,IssuesQuery.PROJECTION,Issues.STATE+"='closed' and "+Issues.GCODE_ID+" = "+gcodeId,null,Issues.DEFAULT_SORT);
				}else{
					mState = 0; //All
					mHandler.startQuery(issuesUri, IssuesQuery.PROJECTION, Issues.DEFAULT_SORT);
				}
			}else
				displayAlert();
		}
	};
	private void updateRefreshStatus() {
		findViewById(R.id.gcode_home_btn_alert).setVisibility(View.GONE);
		findViewById(R.id.gcode_home_btn_refresh).setVisibility(
				mSyncService.isSync() ? View.GONE : View.VISIBLE);
		findViewById(R.id.gcode_home_btn_refresh_progress).setVisibility(
				mSyncService.isSync() ? View.VISIBLE : View.GONE);
	}
	/**
	 * {@link ProjectsAdapter} that renders a {@link ProjectQuery}.
	 */
	private class IssuesAdapter extends CursorAdapter {
		private LayoutInflater mInflater;

		public IssuesAdapter(Context context) {
			super(context, null);
			mInflater = LayoutInflater.from(context);
		}

		/** {@inheritDoc} */
		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			return getLayoutInflater().inflate(R.layout.list_item_issue, parent, false);
		}

		/** {@inheritDoc} */
		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			ViewHolder holder;
			if(view==null){
				view = mInflater.inflate(R.layout.list_item_issue, null);
				holder = new ViewHolder();
				holder.title = (TextView) view.findViewById(R.id.issue_title);
				holder.stuff = (TextView) view.findViewById(R.id.issue_contents);

				view.setTag(holder);
			}else{
				holder = (ViewHolder) view.getTag();
			}

			holder.title.setText(cursor.getString(IssuesQuery.ISSUE_ID)+" - "+cursor
					.getString(IssuesQuery.TITLE));   
			holder.stuff.setText(cursor.getString(IssuesQuery.AUTHOR)+" - "+cursor
					.getString(IssuesQuery.STATUS)+" - "+cursor
					.getString(IssuesQuery.STARS)+" Stars");  
		}


		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if(convertView==null){
				convertView = mInflater.inflate(R.layout.list_item_issue, parent,false);
				holder = new ViewHolder();
				holder.title = (TextView) convertView.findViewById(R.id.issue_title);
				holder.stuff = (TextView) convertView.findViewById(R.id.issue_contents);

				convertView.setTag(holder);
			}else{
				holder = (ViewHolder) convertView.getTag();
			}
			return super.getView(position, convertView, parent);
		}

		@Override
		public void notifyDataSetChanged() {
			// TODO Auto-generated method stub
			super.notifyDataSetChanged();
		}


	}
	static class ViewHolder {
		TextView title;
		TextView stuff;
	}

	/** {@link Projects} query parameters. */
	private interface IssuesQuery {
		String[] PROJECTION = {
				BaseColumns._ID,
				Issues.ISSUE_ID,
				Issues.TITLE,
				Issues.AUTHOR,
				Issues.STATUS,
				Issues.STARS,

		};
		//		int ID = 0;
		int ISSUE_ID = 1;
		int TITLE = 2;
		int AUTHOR = 3;
		int STATUS = 4;
		int STARS = 5;
	}
}
